package com.ruoyi.system.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;

import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.system.domain.PropertyChange;
import com.ruoyi.system.domain.PropertyPicture;
import com.ruoyi.system.mapper.PropertyJiajuMapper;
import com.ruoyi.system.mapper.PropertyPictureMapper;
import com.ruoyi.system.service.IPropertyChangeService;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.PropertyJiaju;
import com.ruoyi.system.service.IPropertyJiajuService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 家具资产Controller
 *
 * @author kite
 * @date 2025-03-25
 */
@RestController
@RequestMapping("/system/jiaju")
public class PropertyJiajuController extends BaseController {
    @Autowired
    private IPropertyJiajuService propertyJiajuService;
    @Autowired
    private PropertyPictureMapper propertyPictureMapper;
    @Autowired
    private IPropertyChangeService propertyChangeService;
    @Autowired
    private PropertyJiajuMapper propertyJiajuMapper;

    /**
     * 查询家具资产列表
     */
    @PreAuthorize("@ss.hasPermi('system:jiaju:list')")
    @GetMapping("/list")
    public TableDataInfo list(PropertyJiaju propertyJiaju) {
        startPage();
        SysUser user = getLoginSysUser();
        Optional<SysRole> first = user.getRoles().stream().filter(role -> "common".equals(role.getRoleKey())).findFirst();
        if (first.isPresent()) {
            propertyJiaju.setCreateBy(getUsername());
        }
        List<PropertyJiaju> list = propertyJiajuService.selectPropertyJiajuList(propertyJiaju);
        return getDataTable(list);
    }

    /**
     * 导出家具资产列表
     */
    @PreAuthorize("@ss.hasPermi('system:jiaju:export')")
    @Log(title = "家具资产", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PropertyJiaju propertyJiaju) {
        List<PropertyJiaju> list = propertyJiajuMapper.selectPropertyJiajuList(propertyJiaju);
        ExcelUtil<PropertyJiaju> util = new ExcelUtil<PropertyJiaju>(PropertyJiaju.class);
        util.exportExcel(response, list, "家具资产数据");
    }

    /**
     * 获取家具资产详细信息
     */

    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(propertyJiajuService.selectPropertyJiajuById(id));
    }

    /**
     * 新增家具资产
     */
    @PreAuthorize("@ss.hasPermi('system:jiaju:add')")
    @Log(title = "家具资产", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PropertyJiaju propertyJiaju) {
        //设备数据中的修订人永远是该系统登入人
        SysUser user = getLoginSysUser();
        propertyJiaju.setRevisedPeople(user.getUserName());//工号
        propertyJiaju.setBackupFields9(user.getNickName());//姓名
        try {
            return toAjax(propertyJiajuService.insertPropertyJiaju(propertyJiaju));
        } catch (ServiceException e) {
            return error(e.getMessage());
        }
    }

    /**
     * 修改家具资产
     */
//    @PreAuthorize("@ss.hasPermi('system:jiaju:edit')")
    @Log(title = "家具资产", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PropertyJiaju propertyJiaju) {
        SysUser user = getLoginSysUser();
        propertyJiaju.setRevisedPeople(user.getUserName());//工号
        propertyJiaju.setBackupFields9(user.getNickName());//姓名
        return toAjax(propertyJiajuService.updatePropertyJiaju(propertyJiaju));
    }

    /**
     * 删除家具资产
     */
    @PreAuthorize("@ss.hasPermi('system:jiaju:remove')")
    @Log(title = "家具资产", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(propertyJiajuService.deletePropertyJiajuByIds(ids));
    }

    /**
     * 导入Excel批量新增家具资产
     */
    @PreAuthorize("@ss.hasPermi('system:jiaju:add')")
    @Log(title = "家具资产导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        try{
            InputStream inputStream = file.getInputStream();
            Workbook workbook = WorkbookFactory.create(inputStream);
            Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表
            int rowCount = sheet.getPhysicalNumberOfRows();

            // 减去表头行
            int dataRowCount = rowCount - 1;

            if (dataRowCount > 10000) {
                throw new ServiceException("导入失败，Excel数据行数不能超过100行，当前行数: " + dataRowCount);
            }
        } catch (IOException e) {
            return AjaxResult.error(e.getMessage());
        }
        propertyJiajuService.importData(file);
        return success("导入成功");
    }

    /**
     * 下载导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<PropertyJiaju> util = new ExcelUtil<>(PropertyJiaju.class);
        util.importTemplateExcel(response, "家具资产数据");
    }

    @PostMapping("/getBatchEditImportTemplate")
    public void getBatchEditImportTemplate(HttpServletResponse response) {
        ExcelUtil<PropertyJiaju> util =
                new ExcelUtil<>(PropertyJiaju.class);
        util.importTemplateExcel(response, "批量修改数据");
    }

    @PreAuthorize("@ss.hasPermi('system:jiaju:edit')")
    @Log(title = "批量修改家具资产", businessType = BusinessType.IMPORT)
    @PostMapping("/batchUpload")
    @RepeatSubmit(interval = 1000, message = "请求过于频繁")
    public AjaxResult batchEdit(MultipartFile file, boolean updateSupport) {
        try{
            InputStream inputStream = file.getInputStream();
            Workbook workbook = WorkbookFactory.create(inputStream);
            Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表
            int rowCount = sheet.getPhysicalNumberOfRows();

            // 减去表头行
            int dataRowCount = rowCount - 1;

            if (dataRowCount > 10000) {
                throw new ServiceException("导入失败，Excel数据行数不能超过100行，当前行数: " + dataRowCount);
            }
        } catch (IOException e) {
            return AjaxResult.error(e.getMessage());
        }
        propertyJiajuService.batchEdit(file);
        return success("导入成功");
    }

    @PostMapping("/uploadPropertyPicture")
    @Transactional
    public AjaxResult uploadPropertyPicture(MultipartFile file, String propertyName) throws Exception {
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePath, file);
        PropertyPicture propertyPicture = new PropertyPicture();
        propertyPicture.setPropertyName(propertyName);
        propertyPicture.setPropertyType("3");
        propertyPicture.setPictureUrl(fileName);
        propertyPicture.setUpload(SecurityUtils.getUsername());
        propertyPicture.setUploadDt(new Date());
        propertyPictureMapper.deleteByNameAndType(propertyName, "3");
        propertyPictureMapper.insertPropertyPicture(propertyPicture);
        return success("上传成功");
    }

    @PreAuthorize("@ss.hasPermi('system:jiaju:list')")
    @GetMapping("/listByChange")
    public List<Map<String, Object>> listByChange(PropertyChange propertyChange) {
        return propertyChangeService.selectByNumberAndType(propertyChange.getInstrumentNumber(), "家具资产");
    }

    /**
     * 获取当前登录用户信息
     *
     * @return 登录用户信息
     */
    @NotNull
    private SysUser getLoginSysUser() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            throw new RuntimeException("请先登录");
        }
        SysUser user = loginUser.getUser();
        if (user == null) {
            throw new RuntimeException("当前用户信息为空");
        }
        return user;
    }
}
